import { defineStore } from 'pinia';
import { getCache, setCache, removeCache } from '@/utils/cache';
import {
	logout as fetchLogout,
	login as fetchLogin,
	getUserInfo as fetchUserInfo,
} from '@/api/auth';

export const useAuthStore = defineStore('user', {
	state: () => {
		return {
			userinfo: {},
			token: '',
		};
	},
	getters: {
		// 是否登录
		isLogin: (state) => {
			return Boolean(state.token);
		},
		getToken: (state) => {
			return state.token;
		},
	},
	actions: {
		initToken() {
			this.token = getCache('token');
		},
		initUserinfo() {
			this.userinfo = getCache('userinfo');
		},
		setToken(token) {
			setCache('token', token);
			this.token = token;
		},
		setUserInfo(userinfo) {
			setCache('userinfo', userinfo);
			this.userinfo = userinfo;
		},
		/**
		 * @description 用户信息
		 */
		async getUserinfo() {
			try {
				const { data } = await fetchUserInfo();
				this.setUserInfo(data);
				return Promise.resolve(data);
			} catch (err) {
				return Promise.reject(err);
			}
		},
		/* 登录退出，重置用户信息等 */
		async logout() {
			try {
				const res = await fetchLogout();
				this.clearAuthStorage();
				return Promise.resolve(res);
			} catch (err) {
				return Promise.reject(err);
			}
		},

		/* 用户登录 */
		async login(username, password) {
			try {
				const { res } = await fetchLogin({ username, password });
				console.log(res);
				// if(res.code === 1){
				// 	await this.handleLoginInfo(res.data)
				// }
				return Promise.resolve(res);
			} catch (e) {
				console.warn('[Login Error]:', e);
				return Promise.reject(e);
			}
		},
		/**
		 * @description 登出
		 */
		async loginOut() {
			try {
				const res = await logout();
				removeCache('token');
				this.setToken('');
				removeCache('userinfo');
				this.setUserInfo({});
				return Promise.resolve(res);
			} catch (err) {
				return Promise.reject(err);
			}
		},
		/* 处理登录返回的数据 */
		async handleLoginInfo(data) {
			this.token = data.token;
			this.userinfo = data;
			// 将token和userInfo保存下来
			setCache('token', data.token);
			setCache('userinfo', data);
		},
	},
});
